﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Dao.CommonDao;
using CSP.Dao.IObjectDaos.CSPBBS;
using CSP.Common.Tools;
using CSP.Model.CSPBBS;
using System.Collections.ObjectModel;
using MySql.Data.MySqlClient;
using System.Data;
using CSP.DataAccess;
using CSP.Common.IProviders;
using CSP.Common.Factories;
using CSP.Model.CSPEnum;

namespace CSP.Dao.ObjectDaos.CSPBBS
{
    class DengluBindInfoDao : CSPBBSCommonDao, IDengLuBindInfoDao
    {
        private const string TABLE = "csp_denglu_bind_info";

        public ICollection<Model.CSPBBS.DengLuBindInfo> FindAll()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 根据Uid返回第三方的登陆信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Model.CSPBBS.DengLuBindInfo GetDataById(int id)
        {
            MySqlConnection conn = MySqlHelperFactory.GetBBSConnection();
            MySqlDataReader reader = null;

            DengLuBindInfo result = null;
            try
            {
                reader = MySqlHelperFactory.ExecuteReader(conn, CommandType.Text, "select * from " + TABLE + " where uid =" + id);
                ICollection<DengLuBindInfo> DengLuBindInfos = ReaderToDengLuBindInfos(reader);
                result = DengLuBindInfos.ElementAtOrDefault(0);
            }
            catch (Exception ex)
            {
                ILoggerProvider provider = LoggerFactory.GetErrorLogger();
                provider.Error("MemberDao.GetDataById", ex);
                throw ex;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                conn.Close();
            }
            return result;
        }


        public DengLuBindInfo GetDataByOtherIdenty(string otherIdenty, UserLoginType userLoginType)
        {
            MySqlConnection conn = MySqlHelperFactory.GetBBSConnection();
            MySqlDataReader reader = null;

            DengLuBindInfo result = null;
            try
            {
                reader = MySqlHelperFactory.ExecuteReader(conn, CommandType.Text, "select * from " + TABLE + " where OtherIdentity ='" + otherIdenty+"' and mediaID="+Convert.ToInt32(userLoginType).ToString());
                ICollection<DengLuBindInfo> DengLuBindInfos = ReaderToDengLuBindInfos(reader);
                result = DengLuBindInfos.ElementAtOrDefault(0);
            }
            catch (Exception ex)
            {
                ILoggerProvider provider = LoggerFactory.GetErrorLogger();
                provider.Error("MemberDao.GetDataById", ex);
                throw ex;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                conn.Close();
            }
            return result;
        }

        public ICollection<Model.CSPBBS.DengLuBindInfo> GeDatatByIds(int[] Ids)
        {
            MySqlConnection conn = MySqlHelperFactory.GetBBSConnection();
            MySqlDataReader reader = null;

            ICollection<DengLuBindInfo> result;
            try
            {
                reader = MySqlHelperFactory.ExecuteReader(conn, CommandType.Text, "select * from " + TABLE + " where uid in (" + string.Join(",", Ids) + ")");
                result = ReaderToDengLuBindInfos(reader);
            }
            catch (Exception ex)
            {
                ILoggerProvider provider = LoggerFactory.GetErrorLogger();
                provider.Error("DengLuBindInfo.GeDatatByIds", ex);
                throw ex;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                conn.Close();
            }

            return result;
        }

        public void Add(Model.CSPBBS.DengLuBindInfo obj)
        {
            MySqlConnection conn = MySqlHelperFactory.GetBBSConnection();

            string insertSql = "insert into " + TABLE + " (Uid,MediaUserID,MediaID,ScreenName,CreateTime,Is_First,Thread_Syn,Log_Syn,Tag,Extendfield1,Extendfield2,Extendfield3,Extendfield4,Extendfield5,OtherIdentity,AccessToken) values";
            insertSql += "(@Uid,@MediaUserID,@MediaID,@ScreenName,@CreateTime,@Is_First,@Thread_Syn,@Log_Syn,@Tag,@Extendfield1,@Extendfield2,@Extendfield3,@Extendfield4,@Extendfield5,@OtherIdentity,@AccessToken)";
            MySqlParameter[] parms = GetParmsForAddOrUpdate(obj);
            try
            {
                int result = MySqlHelperFactory.ExecuteNonQuery(conn, CommandType.Text, insertSql, parms);
            }
            catch (Exception ex)
            {
                ILoggerProvider provider = LoggerFactory.GetErrorLogger();
                provider.Error("DengluBindInfoDao.Add", ex);
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }

        public void Update(DengLuBindInfo obj)
        {
            MySqlConnection conn = MySqlHelperFactory.GetBBSConnection();

            string updateSql = "update " + TABLE + "  set Uid=@Uid,MediaUserID=@MediaUserID,MediaID=@MediaID,ScreenName=@ScreenName,CreateTime=@CreateTime,Is_First=@Is_First,Thread_Syn=@Thread_Syn,Log_Syn=@Log_Syn,Tag=@Tag,Extendfield1=@Extendfield1,Extendfield2=@Extendfield2,Extendfield3=@Extendfield3,Extendfield4=@Extendfield4,Extendfield5=@Extendfield5,OtherIdentity=@OtherIdentity,AccessToken=@AccessToken where uid=@uid";

            MySqlParameter[] parms = GetParmsForAddOrUpdate(obj);
            try
            {
                int result = MySqlHelperFactory.ExecuteNonQuery(conn, CommandType.Text, updateSql, parms);
            }
            catch (Exception ex)
            {
                ILoggerProvider provider = LoggerFactory.GetErrorLogger();
                provider.Error("DengLuBindInfo.Update", ex);
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }

        public Model.CSPBBS.DengLuBindInfo DeleteById(int id)
        {
            DengLuBindInfo dengLuBindInfo = this.GetDataById(id);
            MySqlConnection conn = MySqlHelperFactory.GetBBSConnection();

            string deleteSql = "delete from " + TABLE + " where uid=" + id;

            try
            {
                int result = MySqlHelperFactory.ExecuteNonQuery(conn, CommandType.Text, deleteSql);
            }
            catch (Exception ex)
            {
                ILoggerProvider provider = LoggerFactory.GetErrorLogger();
                provider.Error("DengLuBindInfo.DeleteById", ex);
                throw ex;
            }
            finally
            {
                conn.Close();
            }

            return dengLuBindInfo;
        }


        private ICollection<DengLuBindInfo> DataSetToDengLuBindInfos(DataSet ds)
        {
            ICollection<DengLuBindInfo> result = new Collection<DengLuBindInfo>();
            if (ds.Tables.Count == 0)
            {
                return result;
            }
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                DengLuBindInfo DengLuBindInfo = ObjsToDengLuBindInfo<DataRow>(ds.Tables[0].Rows[i]);
                result.Add(DengLuBindInfo);
            }
            return result;
        }

        private ICollection<DengLuBindInfo> ReaderToDengLuBindInfos(MySqlDataReader reader)
        {
            ICollection<DengLuBindInfo> result = new Collection<DengLuBindInfo>();
            int i = 0;
            do
            {

                while (reader.Read())
                {
                    DengLuBindInfo DengLuBindInfo = ObjsToDengLuBindInfo<MySqlDataReader>(reader);
                    result.Add(DengLuBindInfo);
                }
                i++;
            } while (reader.NextResult()); //NextResult()移动到下一个记录集 

            return result;
        }

        /// <summary>
        /// 将数组数据做对象对配转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objs"></param>
        /// <returns></returns>
        private DengLuBindInfo ObjsToDengLuBindInfo<T>(T objs)
        {
            if (objs == null)
            {
                return null;
            }
            //获取当前实例类型
            Type type = objs.GetType();
            //获取实例索引器
            var property = type.GetProperty("Item", new Type[] { typeof(string) });

            //创建返回值实例
            DengLuBindInfo result = new DengLuBindInfo();

            result.Uid = Convert.ToInt32(property.GetValue(objs, new object[] { "Uid" }));
            result.MediaUserID = Convert.ToInt32(property.GetValue(objs, new object[] { "MediaUserID" }).ToString());
            result.MediaID = Convert.ToInt32(property.GetValue(objs, new object[] { "MediaID" }).ToString());
            result.ScreenName = property.GetValue(objs, new object[] { "ScreenName" }).ToString();
            result.CreateTime = CommonTool.ConvertToDateTime(Convert.ToDouble(property.GetValue(objs, new object[] { "CreateTime" })));
            result.Is_First = Convert.ToInt32(property.GetValue(objs, new object[] { "Is_First" }).ToString());
            result.Thread_Syn = Convert.ToInt32(property.GetValue(objs, new object[] { "Thread_Syn" }).ToString());
            result.Log_Syn = Convert.ToInt32(property.GetValue(objs, new object[] { "Log_Syn" }).ToString());
            result.Tag = Convert.ToInt32(property.GetValue(objs, new object[] { "Tag" }));
            result.Extendfield1 = Convert.ToInt32(property.GetValue(objs, new object[] { "Extendfield1" }).ToString());
            result.Extendfield2 = property.GetValue(objs, new object[] { "Extendfield2" }).ToString();
            result.Extendfield3 = Convert.ToInt32(property.GetValue(objs, new object[] { "Extendfield3" }).ToString());
            result.Extendfield4 = property.GetValue(objs, new object[] { "Extendfield4" }).ToString();
            result.Extendfield5 = Convert.ToInt32(property.GetValue(objs, new object[] { "Extendfield5" }).ToString());
            result.OtherIdenty = property.GetValue(objs, new object[] { "OtherIdentity" }).ToString();
            result.AccessToken = property.GetValue(objs, new object[] { "AccessToken" }).ToString();
            return result;
        }

        private MySqlParameter[] GetParmsForAddOrUpdate(DengLuBindInfo DengLuBindInfo)
        {
            MySqlParameter[] parms = new MySqlParameter[] {
                //GetParameter("uid",DbType.Int32,8,DengLuBindInfo.Id),
                GetParameter("@Uid",DbType.Int32,11,DengLuBindInfo.Uid),
                GetParameter("@MediaUserID",DbType.Int64,32,DengLuBindInfo.MediaUserID),
                GetParameter("@MediaID",DbType.Int64,32,DengLuBindInfo.MediaID),
                GetParameter("@ScreenName",DbType.String,250,DengLuBindInfo.ScreenName),
                GetParameter("@CreateTime",DbType.Int32,10,CommonTool.ConvertToTimeSpan(DengLuBindInfo.CreateTime)),
                GetParameter("@Is_First",DbType.Int32,1,DengLuBindInfo.Is_First),
                GetParameter("@Thread_Syn",DbType.Int32,1,DengLuBindInfo.Thread_Syn),
                GetParameter("@Log_Syn",DbType.Int32,1,DengLuBindInfo.Log_Syn),
                GetParameter("@Tag",DbType.Int32,1,DengLuBindInfo.Tag),
                GetParameter("@Extendfield1",DbType.Int32,1,DengLuBindInfo.Extendfield1),
                GetParameter("@Extendfield2",DbType.String,250,DengLuBindInfo.Extendfield2),
                GetParameter("@Extendfield3",DbType.Int32,1,DengLuBindInfo.Extendfield3),
                GetParameter("@Extendfield4",DbType.String,250,DengLuBindInfo.Extendfield4),
                GetParameter("@Extendfield5",DbType.Int32,1,DengLuBindInfo.Extendfield5),
                GetParameter("@OtherIdentity",DbType.String,50,DengLuBindInfo.OtherIdenty),
                GetParameter("@AccessToken",DbType.String,100,DengLuBindInfo.AccessToken)
            };

            return parms;
        }

    }
}
